package com.miya.demo.handler.order;


import groovy.util.logging.Slf4j;

/**
 * 订单处理管道
 *
 * @author CaiXiaowei
 * @date 2022/09/30
 */
@Slf4j
public class OrderHandlerPipeline<T> {


    OrderHandlerChainContext headerChainContext;

    public OrderHandlerPipeline() {

        headerChainContext = new OrderHandlerChainContext(new AbstractOrderHandler() {
            @Override
            public void doWork(OrderHandlerChainContext handlerChainContext, Object request) {
                headerChainContext.fireNextContext(request);
            }

            @Override
            public void cancelWork(OrderHandlerChainContext handlerChainContext, Object request) {
                headerChainContext.firePrevContext(request);
            }
        });
    }

    /**
     * 处理请求, 责任链入口
     *
     * @param t t
     */
    public void processRequest(T t) {
        headerChainContext.handler(t);
    }


    /**
     * 添加责任链
     *
     * @param abstractHandler 抽象处理程序
     */
    public void addLast(AbstractOrderHandler abstractHandler) {
        OrderHandlerChainContext context = headerChainContext;
        while (context.next != null) {
            context = context.next;
        }
        OrderHandlerChainContext newCxt = new OrderHandlerChainContext(abstractHandler);
        context.next = newCxt;
        newCxt.prev = context;

        System.out.println("OrderHandlerPipeline--->addLast");
        System.out.println(context);
    }
}
